package com.td.core.obj.tower;

import java.util.List;

import com.td.core.obj.TDMap;
import com.td.core.obj.TDObject;
import com.td.core.obj.TDPoint;
import com.td.core.obj.bullet.Bullet;
import com.td.core.obj.unit.Unit;
import com.td.core.obj.utils.PointConverter;
import com.td.core.obj.utils.TDTimer2;
import com.td.core.obj.utils.TDVector;

public abstract class Tower extends TDObject {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private final static int TOWER_SIZE = 2;
	
	private TDTimer2 attackTimer;
	private boolean attackReady;
	
	private float newRotation;
	
	public Tower(int x, int y) {
		super(x, y);
		attackTimer = new TDTimer2(calculateAttackDelay(getAttackSpeed()));
	}

	public Tower(Tower tower) {
		this(tower.getPosition().getX(), tower.getPosition().getY());
	}
	
	public long calculateAttackDelay(int attack) {
		
		return 66 - attack * 6;
	}
	
	public abstract int getPrice();
	
	public abstract int getRange();
	
	public abstract int getMinDamage();
	
	public abstract int getMaxDamage();
	
	public abstract int getSplash();
	
	public abstract int getAttackSpeed();
	
	public abstract String getName();
	
//	private void rotate() {
//		
//		float actRotation = getRotation();
//		float dR = 1.f;
//		
//		if(newRotation > actRotation) {			
//			actRotation += dR;
//			System.out.println(newRotation +", "+ actRotation +", plus");
//		} else {
//			actRotation -= dR;
//			System.out.println(newRotation +", "+ actRotation +", minus");
//		}
//		
//		setRotation(actRotation % 360);
//			
//	}
	
	public Unit attack(List<Unit> units) {
	
		Unit bestUnit = null;
		float bestDistance = 10000;
		
		if(attackTimer.update()) {
			
			attackReady = true;
		}
		
		if(!units.isEmpty()) {
			for(Unit unit : units) {	
				TDVector realPosition = PointConverter.toTDVector(getPosition()).add(new TDVector(TDMap.DrawParams.FIELD_SIZE, TDMap.DrawParams.FIELD_SIZE));
				float distance = realPosition.distance(unit.getRealPosition());
				if(distance <= getRange() * TDMap.DrawParams.FIELD_SIZE && distance < bestDistance) {
					bestUnit = unit;
					bestDistance = distance;
					newRotation = (float) realPosition.sub(new TDVector(unit.getRealPosition())).getTheta();
					
					newRotation += 270;
					newRotation %= 360;
					//rotate();
					setRotation(newRotation);
				}
			}
			
			
			
		}
		if(attackReady)
			return bestUnit;
		
		return null;
	}
	
	public int getSize() {
		return TOWER_SIZE;
	}
	
	public Bullet createBullet(Unit attackedUnit) {
		
		Bullet bullet = new Bullet(new TDPoint(getPosition().getX() + 1, getPosition().getY() + 1), attackedUnit);
		bullet.setMinDamage(getMinDamage());
		bullet.setMaxDamage(getMaxDamage());
		bullet.setSplash(getSplash());
		
		attackReady = false;
		attackTimer.restart();
		
		return bullet;
	}	
	
}
